package com.intct.flink;

import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.configuration.RestOptions;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

/**
 * @author gufg
 * @since 2025-06-23 11:15
 */
public class WroldCountDemo {
    public static void main(String[] args) throws Exception {
        Configuration conf = new Configuration();
        conf.set(RestOptions.BIND_PORT, "8081");
        // 获取环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);

        // 源
        DataStreamSource<String> socketTextStream = env.socketTextStream("jd-node", 8888);

        // 操作处理
        // hello flink
        SingleOutputStreamOperator<Tuple2<String, Integer>> flatMapDS =
                socketTextStream.flatMap(new FlatMapFunction<String, Tuple2<String, Integer>>() {

            @Override
            public void flatMap(String value, Collector<Tuple2<String, Integer>> out) throws Exception {
                // 分隔 hellp  / hello flink
                String[] worlds = value.split(" ");
                for (String world : worlds) {
                    // Tuple2 String Int
                    out.collect(Tuple2.of(world, 1));
                }
            }
        });

        SingleOutputStreamOperator<Tuple2<String, Integer>> filterDS = flatMapDS.filter(new FilterFunction<Tuple2<String, Integer>>() {
            @Override
            public boolean filter(Tuple2<String, Integer> value) throws Exception {
                if (value.equals("flink")) {
                    return true;
                }
                return false;
            }
        }).disableChaining();

        SingleOutputStreamOperator<Tuple2<String, Integer>> sumDS = filterDS.keyBy(new KeySelector<Tuple2<String, Integer>, String>() {
            @Override
            public String getKey(Tuple2<String, Integer> value) throws Exception {
                return value.f0;
            }
        }).sum(1);

        // 输出
        sumDS.print();

        // 启动作业
        env.execute();

    }
}
